package cn.a.bootexe;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Created by xuxingcan on 16-11-3.
 */
public class BootReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(final Context context, Intent intent) {
        Log.i("xuxingcan", "onReceive  " + intent.getAction());
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
//                    Thread.sleep(10 * 1000);
                    Log.i("xuxingcan", "start");
                    String path = new File(context.getCacheDir(), "busybox-armv7l").getAbsolutePath();
                    copyBigDataToSD(context, "busybox-armv7l", path);
                    MainActivity.exec("chmod 777 " + path);

                    path = new File(context.getCacheDir(), "start.sh").getAbsolutePath();
                    copyBigDataToSD(context, "start.sh", path);
                    Log.i("xuxingcan", "copy start.sh");
                    MainActivity.exec("chmod 777 " + path);
                    MainActivity.exec("sh " + path);
                    Log.i("xuxingcan", "sh");
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.i("xuxingcan", "Exception\n" + e.getMessage());
                }
//                Log.i("xuxingcan", "start");
//                MainActivity.exec("cat /storage/sdcard0/shenji/WCDMA.conf > /data/weirdo/W/WCDMA.conf");
//                Log.i("xuxingcan", "DONE cat");
//                MainActivity.exec("chmod -R  777 /data/weirdo");
//                Log.i("xuxingcan", "DONE chmod");
//                MainActivity.exec("sh /data/weirdo/W/启动.sh");
//                Log.i("xuxingcan", "DONE sh");
            }
        }).start();
    }

    private void copyBigDataToSD(Context mContext, String name, String strOutFileName) throws Exception {
        InputStream myInput;
        OutputStream myOutput = new FileOutputStream(strOutFileName);
        myInput = mContext.getAssets().open(name);
        byte[] buffer = new byte[1024];
        int length = myInput.read(buffer);
        while (length > 0) {
            myOutput.write(buffer, 0, length);
            length = myInput.read(buffer);
        }
        myOutput.flush();
        myInput.close();
        myOutput.close();
    }
}
